<template>
  <el-dialog :model-value="visible" title="编辑" width="500px" :close-on-click-modal="false" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="root-node-form">
      <el-form-item label="根节点名称" prop="warehouseName">
        <el-input v-model="form.warehouseName" placeholder="请输入" class="full-width" />
      </el-form-item>

      <el-form-item label="备注" prop="remarks">
        <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入备注" class="full-width" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { updateWarehouse } from '@/Https/server'

// Props
interface Props {
  visible: boolean
  warehouse?: any
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)

// 表单数据
const form = reactive({
  id: '',
  warehouseName: '',
  remarks: ''
})

// 表单验证规则
const rules: FormRules = {
  warehouseName: [
    { required: true, message: '请输入根节点名称', trigger: 'blur' },
    { min: 2, max: 100, message: '根节点名称长度在 2 到 100 个字符', trigger: 'blur' }
  ]
}

// 方法
const resetForm = () => {
  Object.assign(form, {
    id: '',
    warehouseName: '',
    remarks: ''
  })

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const initForm = () => {
  if (props.warehouse) {
    Object.assign(form, {
      id: props.warehouse.id,
      warehouseName: props.warehouse.warehouseName,
      remarks: props.warehouse.remarks || ''
    })
  } else {
    resetForm()
  }
}

const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    const response: any = await updateWarehouse(form)

    if (response.code === 200) {
      emit('success')
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败，请检查表单数据')
  } finally {
    submitting.value = false
  }
}

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})
</script>

<style scoped>
.root-node-form {
  padding: 20px 0;
}

.full-width {
  width: 100%;
}

.dialog-footer {
  text-align: center;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}
</style>